<template>
  <div>
    <Table
      ref="tablesMain"
      :data="insideTableData"
      :columns="insideColumns"
      :stripe="stripe"
      :border="border"
      :show-header="showHeader"
      :width="width"
      :height="height"
      :loading="loading"
      :disabled-hover="disabledHover"
      :highlight-row="highlightRow"
      :row-class-name="rowClassName"
      :size="size"
      :no-data-text="noDataText"
      :no-filtered-data-text="noFilteredDataText"
      @on-current-change="onCurrentChange"
      @on-select="onSelect"
      @on-select-cancel="onSelectCancel"
      @on-select-all="onSelectAll"
      @on-selection-change="onSelectionChange"
      @on-sort-change="onSortChange"
      @on-filter-change="onFilterChange"
      @on-row-click="onRowClick"
      @on-row-dblclick="onRowDblclick"
      @on-expand="onExpand"
    >
      <slot name="header" slot="header"></slot>
      <slot name="footer" slot="footer"></slot>
      <slot name="loading" slot="loading"></slot>
    </Table>
    <div
      :class="{'table-footer':JSON.stringify(otherData)!=='{}'||JSON.stringify(footerData)!=='[]'}"
    >
      <div v-if="JSON.stringify(otherData)!=='{}'" class="tiptext">
        <span>会员预计分佣{{otherData.memberbenefit}}</span>
        <span>分站预计收入{{otherData.sitebenefit}}</span>
        <span>分站实际收入{{otherData.sitebenefit2}}</span>
      </div>
      <div v-if="JSON.stringify(footerData)!=='[]'" class="tiptext">
        <span v-for="(item,index) in footerData" :key="index">{{item}}</span>
      </div>
      <div v-if="page.pageNumber" class="page">
        <Page
          :current="page.pageNumber"
          :total="page.totalRow"
          :page-size="page.pageSize"
          show-total
          show-elevator
          @on-change="handleChange($event)"
        />
      </div>
    </div>
    <a id="hrefToExportTable" style="display: none;width: 0px;height: 0px;"></a>
  </div>
</template>

<script>
import TablesEdit from "./edit.vue";
import handleBtns from "./handle-btns";
import { setDate } from "@/libs/tools";
import "./index.less";
export default {
  name: "Tables",
  props: {
    // 表格左下的显示字段
    otherData: {
      type: Object,
      default() {
        return {};
      }
    },
    lookALLBtn:{
      type: Boolean,
      default: true
    },
    exportLoading: {
      type: Boolean,
      default: false
    },
    importLoading: {
      type: Boolean,
      default: false
    },
    footerData: {
      type: Array,
      default() {
        return [];
      }
    },
    // 需要查询的数字区间
    numSection: {
      type: Array,
      default() {
        return [];
      }
    },
    // 需要添加的搜索list(如果列表展示里面没有相关字段)、
    extraList: {
      type: Array,
      default() {
        return [];
      }
    },
    area: {
      type: Array,
      default() {
        return [];
      }
    },
    // 时间查询
    dataSearch: {
      type: Array,
      default() {
        return [];
      }
    },
    cascaderList: {
      type: Array,
      default() {
        return [];
      }
    },
    // 是否展示自带的查询
    searchBtn: {
      type: Boolean,
      default: true
    },
    //
    dataDownShow: {
      type: Boolean,
      default: false
    },
    handleChange: {
      type: Function
    },
    dataDownLoad: {
      type: Function
    },
    changeFn: {
      type: Array,
      default() {
        return [];
      }
    },
    search: {
      type: Function
    },
    filterList: {
      type: Array,
      default() {
        return [];
      }
    },
    buttonText: {
      type: String
    },
    buttonText1: {
      type: String
    },
    buttonText2: {
      type: String
    },
    add: {
      type: Function
    },
    addImport: {
      type: Function
    },
    addImport2: {
      type: Function
    },
    value: {
      type: Array,
      default() {
        return [];
      }
    },
    columns: {
      type: Array,
      default() {
        return [];
      }
    },
    page: {
      type: Object,
      default() {
        return {};
      }
    },
    size: String,
    width: {
      type: [Number, String]
    },
    height: {
      type: [Number, String]
    },
    stripe: {
      type: Boolean,
      default: false
    },
    border: {
      type: Boolean,
      default: false
    },
    showHeader: {
      type: Boolean,
      default: true
    },
    highlightRow: {
      type: Boolean,
      default: false
    },
    rowClassName: {
      type: Function,
      default() {
        return "";
      }
    },
    context: {
      type: Object
    },
    /**
     * @description 没有数据的显示文字
     */
    noDataText: {
      type: String
    },

    noFilteredDataText: {
      type: String
    },
    /**
     * @description 禁用的hover
     */
    disabledHover: {
      type: Boolean
    },
    /**
     * @description 表格的loading加载
     */
    loading: {
      type: Boolean,
      default: false
    },
    /**
     * @description 全局设置是否可编辑
     */
    editable: {
      type: Boolean,
      default: false
    },
    /**
     * @description 是否可搜索
     */
    searchable: {
      type: Boolean,
      default: true
    },
    /**
     * @description 查看全部的函数
     */
    lookALL: {
      type: Function,
      default() {
        return "";
      }
    }
    /**
     * @description 设置搜的默认值
     *
     */
  },
  /**
   * Events
   * @on-start-edit 返回值 {Object} ：同iview中render函数中的params对象 { row, index, column }
   * @on-cancel-edit 返回值 {Object} 同上
   * @on-save-edit 返回值 {Object} ：除上面三个参数外，还有一个value: 修改后的数据
   * 有关查询的格式如下在组件应用的页面填入
   * 时间区间搜索格式  [{}];
   * dataSearch:[
          {
            id: '1',
            key:'xxxx',//自己定义
            start:{key:'createtime_start',value:''},写时间区间的开始key,和开始初始值
            end:{key:'createtime_end',value:''},写时间区间的结束key,和结束初始值
            title:'xxxx'  对应的title
          },
      ],
      数字次数区间[{}]
     * numSection:[
         {
            id: '1',
            key:'xxx',自定义
            start:{key:'buytimes_start',value:0},//查询开始初始值
            end:{key:'buytimes_end',value:0},/查询结束初始值value最好是0(数字输框，类型为Number,支持小数)
            title:'xxxx'对应显示的title
          },
      ],
     * filterList[
          {
            id: 'provinceid',
            select:true,
            name: '省份',
            data: []
          },
      ]如上列所示select?'为下拉框模式':'单选模式'id对应的查询字段data为选择的列表
    * 输入框的查询在页面的每行数据填入时在对应的字段加如searchable: true,自动添加到搜索。次序为数据的排列次序。
    * 默认显示所有的搜索和查看全部。使用searchBtn=false取消显示
   */
  data() {
    return {
      small: "small", //按钮的大小
      tabSearch: {}, //tab的点选数据
      searchdata: {}, //所有的搜索数据
      lastList: [], //input查询list
      inputSearch: [], //搜索框得搜索
      insideColumns: [], //tab
      insideTableData: [],
      edittingCellId: "",
      edittingText: "",
      searchValue: [],
      searchKey: "",
      startAndEndValue: "",
      numSectionKey: this.numSection.length > 0 ? this.numSection[0].key : "",
      filterKey: this.filterList.map((item, index) =>
        item.data.length > 0 ? item.data[0].id : ""
      ), //选项没有默认值就默认第一项
      // area:[]
      cascaderObj: {},
      cascaderArr: []
    };
  },
  created() {},
  computed: {
    // filterKey(){
    //   return this.filterList.map(item=>{
    //     let newItem = item;
    //     newItem.key = item.id;
    //     newItem.value = '';
    //     return newItem
    //   })
    // }
  },
  methods: {
    // 查看全部回复默认值
    all() {
      // (this.filterKey = this.filterList.map((item, index) =>
      //   item.data.length > 0 ? item.data[0].id : ""
      // )),
      (this.filterKey = this.filterList.map((item, index) => {
        if (
          item.id !== "provinceid" &&
          item.id !== "cityid" &&
          item.id !== "townid"
        ) {
          return item.data.length > 0 ? item.data[0].id : "";
        }
      })),
        (this.searchValue = []); //手机号等单独项得查询
      this.searchdata = {};
      this.tabSearch = {}; //清空旧数据
      this.numSection.forEach((val, index) => {
        this.numSection[index].start.value = "";
        this.numSection[index].end.value = "";
      });
      this.dataSearch.forEach((el, index) => {
        el.start.value = "";
        el.end.value = "";
      });
      this.cascaderArr = [];
      let allData = { page: 1 };
      this.lookALL(allData);
    },
    // 点击单选
    filter() {
      let data = {};
      this.filterList.forEach((item, index) => {
        if (this.filterKey[index]) {
          data[item.id] = this.filterKey[index];
        }
      });
      this.datasGroup();
      this.tabSearch = data; //点击搜索的查询项目
    },
    // 点击单选
    filterCascader(idName, e) {
      let obj = {};
      obj[idName] = e;
      this.cascaderObj = obj;
    },
    // 支持编辑表格
    suportEdit(item, index) {
      item.render = (h, params) => {
        return h(TablesEdit, {
          props: {
            params: params,
            value: this.insideTableData[params.index][params.column.key],
            edittingCellId: this.edittingCellId,
            editable: this.editable
          },
          on: {
            input: val => {
              this.edittingText = val;
            },
            "on-start-edit": params => {
              this.edittingCellId = `editting-${params.index}-${params.column.key}`;
              this.$emit("on-start-edit", params);
            },
            "on-cancel-edit": params => {
              this.edittingCellId = "";
              this.$emit("on-cancel-edit", params);
            },
            "on-save-edit": params => {
              this.value[params.row.initRowIndex][
                params.column.key
              ] = this.edittingText;
              this.$emit("input", this.value);
              this.$emit(
                "on-save-edit",
                Object.assign(params, { value: this.edittingText })
              );
              this.edittingCellId = "";
            }
          }
        });
      };
      return item;
    },
    surportHandle(item) {
      let options = item.options || [];
      let insideBtns = [];
      options.forEach(item => {
        if (handleBtns[item]) insideBtns.push(handleBtns[item]);
      });
      let btns = item.button ? [].concat(insideBtns, item.button) : insideBtns;
      item.render = (h, params) => {
        params.tableData = this.value;
        return h("div", btns.map(item => item(h, params, this)));
      };
      return item;
    },
    // 表头设置
    handleColumns(columns) {
      this.insideColumns = columns.map((item, index) => {
        let res = item;
        if (res.editable) res = this.suportEdit(res, index);
        if (res.key === "handle") res = this.surportHandle(res);
        return res;
      });
    },
    // 设置但选项的默认值
    setDefaultSearchKey() {
      this.searchKey =
        this.columns[0].key !== "handle"
          ? this.columns[0].key
          : this.columns.length > 1
          ? this.columns[1].key
          : "";
    },
    handleClear(e) {
      if (e.target.value === "") this.insideTableData = this.value;
    },
    // 组装数据
    datasGroup() {
      this.inputSearch = []; //input输入的单个选项搜索
      let senData = {}; //需要搜索的数据
      let timeList = []; //时间区间数组
      // 数字区间，如有新值需在组件应用页面numSection数组中添加相关的字段
      let sections = [];
      if (this.numSection.length > 0) {
        this.numSection.forEach((val, index) => {
          sections.push(val.end, val.start);
        });
      }
      if (sections.length > 0) {
        sections.forEach(ele => {
          // if (ele.value >= 0) {
          senData[ele.key] = ele.value;
          // }
        });
      }
      // 日期搜索查询数据拼装
      if (this.dataSearch.length > 0) {
        this.dataSearch.forEach((val, index) => {
          timeList.push(val.end, val.start);
        });
      }
      if (timeList.length > 0) {
        timeList.forEach(ele => {
          if (ele.value) {
            senData[ele.key] = setDate(ele.value.getTime(), "YYYY-MM-DD");
          }
        });
      }
      //手机号等输入框查询
      this.searchValue.forEach((el, index) => {
        this.inputSearch.push({ key: this.lastList[index].key, value: el });
      });
      if (this.inputSearch.length > 0) {
        this.inputSearch.forEach(el => {
          senData[el.key] = el.value;
        });
      }
      this.searchdata = senData;
    },
    // 输入框的查询按钮
    handleSearch() {
      this.datasGroup();
      this.searchdata = Object.assign(
        this.tabSearch,
        this.searchdata,
        this.cascaderObj
      );
      this.search(this.searchKey, this.searchValue, this.searchdata);
    },
    // 表格数据填充
    handleTableData() {
      this.insideTableData = this.value.map((item, index) => {
        let res = item;
        res.initRowIndex = index;
        return res;
      });
    },
    exportCsv(params) {
      this.$refs.tablesMain.exportCsv(params);
    },
    clearCurrentRow() {
      this.$refs.talbesMain.clearCurrentRow();
    },
    onCurrentChange(currentRow, oldCurrentRow) {
      this.$emit("on-current-change", currentRow, oldCurrentRow);
    },
    onSelect(selection, row) {
      this.$emit("on-select", selection, row);
    },
    onSelectCancel(selection, row) {
      this.$emit("on-select-cancel", selection, row);
    },
    onSelectAll(selection) {
      this.$emit("on-select-all", selection);
    },
    onSelectionChange(selection) {
      this.$emit("on-selection-change", selection);
    },
    onSortChange(column, key, order) {
      this.$emit("on-sort-change", column, key, order);
    },
    onFilterChange(row) {
      this.$emit("on-filter-change", row);
    },
    onRowClick(row, index) {
      this.$emit("on-row-click", row, index);
    },
    onRowDblclick(row, index) {
      this.$emit("on-row-dblclick", row, index);
    },
    onExpand(row, status) {
      this.$emit("on-expand", row, status);
    },
    // 可以添加的搜索框
    addSearchValue(arr, addArr) {
      let a = arr.filter(Item => Item.searchable);
      if (addArr.length > 0) {
        this.lastList = a.concat(addArr);
      } else {
        this.lastList = a;
      }
    }
  },
  watch: {
    columns(columns) {
      
      this.handleColumns(columns);
      this.setDefaultSearchKey();
    },
    value(val) {
      this.handleTableData();
    }
  },
  mounted() {
    this.handleColumns(this.columns);
    this.setDefaultSearchKey();
    this.handleTableData();
    this.addSearchValue(this.columns, this.extraList);
  }
};
</script>
